package com.larissa.android.quiz;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.larissa.android.quiz.databinding.ActivityMainBinding;
import com.larissa.android.quiz.databinding.ChooseAnswerBinding;
import com.larissa.android.quiz.databinding.InputAnswerBinding;
import com.larissa.android.quiz.question.Question;

import java.util.List;
import java.util.Objects;


public class MainActivity extends AppCompatActivity {

    //问题文本区、选择区和输入区的binding
    private ActivityMainBinding textBinding;
    private ChooseAnswerBinding chooseAnswerBinding;
    private InputAnswerBinding inputAnswerBinding;

    private final String TAG = "MainActivity";
    private List<Question> questions;

/*    private int questionIndex;
    private int numberOfRightAnswers;

    private boolean showed = false;
    private String time = " ";*/

    private MainViewModel vm;

    private ActivityResultLauncher<Intent> helpLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate() called");
        //获取来自WelcomeActivity的意图的题目类型标志
        int flag = getIntent().getIntExtra("flag", WelcomeActivity.GEOGRAPHY);
/*        if (savedInstanceState != null) {
            questionIndex = savedInstanceState.getInt("questionIndex");
            numberOfRightAnswers = savedInstanceState.getInt("numberOfRightAnswers");
        } else {
            questionIndex = 0;
            numberOfRightAnswers = 0;
        }*/
        //程序运行数据
        vm = new ViewModelProvider(this).get(MainViewModel.class);
        int orientation = getResources().getConfiguration().orientation;
        LinearLayout linearLayout;
        if (flag == WelcomeActivity.GEOGRAPHY) {
            questions = vm.getGeoQuestions();
            Objects.requireNonNull(getSupportActionBar()).setTitle("GEOGRAPHY");
            chooseAnswerBinding = ChooseAnswerBinding.inflate(getLayoutInflater());
            textBinding = chooseAnswerBinding.tvQuestion;
            linearLayout = chooseAnswerBinding.getRoot();
            //如果答题已完成，则禁用选择按钮；否则为按钮添加点击事件
            if (vm.getQuestionIndex() == -1)
                disableChooseBtn();
            else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                chooseAnswerBinding.btnTrue.setOnClickListener(this::chooseBtnClick);
                chooseAnswerBinding.btnFalse.setOnClickListener(this::chooseBtnClick);
                chooseAnswerBinding.btnHelp.setOnClickListener(this::showHelp);
            } else {
                chooseAnswerBinding.btnCheck.setOnClickListener(this::chooseBtnClick);
                chooseAnswerBinding.btnClear.setOnClickListener(this::chooseBtnClick);
                chooseAnswerBinding.btnHelpLand.setOnClickListener(this::showHelp);
            }

        } else {
            //标志为其他（目前只有数学题），则在viewGroup添加输入区
            questions = vm.getMathQuestions();
            Objects.requireNonNull(getSupportActionBar()).setTitle("MATHEMATICS");
            inputAnswerBinding = InputAnswerBinding.inflate(getLayoutInflater());
            textBinding = inputAnswerBinding.tvQuestion;
            linearLayout = inputAnswerBinding.getRoot();
            //如果答题已完成，则禁用提交按钮；否则为按钮添加点击事件
            if (vm.getQuestionIndex() == -1)
                disableInputSubmit();
            else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                inputAnswerBinding.btnSubmit.setOnClickListener(this::inputSubmitClick);
                inputAnswerBinding.btnHelp.setOnClickListener(this::showHelp);
            } else {
                inputAnswerBinding.btnSubmitLand.setOnClickListener(this::inputSubmitClick);
                inputAnswerBinding.btnHelpLand.setOnClickListener(this::showHelp);
            }
        }
        textBinding.tvQuestion.setText(vm.getQuestionIndex() == -1 ?
                questions.get(questions.size() - 1).getQuestionText()
                : questions.get(vm.getQuestionIndex()).getQuestionText());
        setContentView(linearLayout);




        helpLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent resultData = result.getData();
            vm.setShowed(resultData.getBooleanExtra("showed", false));
            vm.setTime(resultData.getStringExtra("time"));
        });
    }

    /**
     * 帮助按钮的功能，打开HelpActivity
     *
     * @param v
     */
    private void showHelp(View v) {
        Intent intent = new Intent(this, HelpActivity.class);
        intent.putExtra("answer", questions.get(vm.getQuestionIndex()));
        helpLauncher.launch(intent);
    }

/*    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState() called.");
        outState.putInt("questionIndex", questionIndex);
        outState.putInt("numberOfRightAnswers", numberOfRightAnswers);
    }*/


    /**
     * 选择区的答题判断
     *
     * @param v 点击的控件
     */
    private void chooseBtnClick(View v) {
        //如果被按下的控件是R.id.btn_check或R.id.btn_true，则用户选择的答案为true，否则为false
        boolean userAnswer = (v.getId() == R.id.btn_check) || (v.getId() == R.id.btn_true);
        Question question = questions.get(vm.getQuestionIndex());
        //判断用户的答案是否正确
        boolean result = String.valueOf(userAnswer).equals(question.getQuestionAnswer());
        //如果回答正确，则正确答案数加1
        if (vm.isShowed()) {
            Toast.makeText(this, "invalid in " + vm.getTime(), Toast.LENGTH_SHORT).show();
            vm.setHelpTimes(vm.getHelpTimes() + 1);
        } else if (result) {
            vm.rightAnswersPP();
        }else {
            vm.setWrongTimes(vm.getWrongTimes() + 1);
        }
        vm.setShowed(false);
        //如果答题结束，则将问题索引设置为-1，禁用按键，并弹出Toast；如果没结束，则问题索引加1，更改文本区的问题文本
        if (vm.getQuestionIndex() >= questions.size() - 1) {
            vm.setQuestionIndex(-1);
            disableChooseBtn();
            showResult();
        } else {
            vm.questionIndexPP();
            textBinding.tvQuestion.setText(questions.get(vm.getQuestionIndex()).getQuestionText());
        }
    }

    /**
     * 禁用选择区的按钮
     */
    private void disableChooseBtn() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            chooseAnswerBinding.btnTrue.setEnabled(false);
            chooseAnswerBinding.btnFalse.setEnabled(false);
            chooseAnswerBinding.btnHelp.setEnabled(false);
        } else {
            chooseAnswerBinding.btnCheck.setEnabled(false);
            chooseAnswerBinding.btnClear.setEnabled(false);
            chooseAnswerBinding.btnHelpLand.setEnabled(false);
        }
    }

    /**
     * 输入区的答题判断
     *
     * @param v
     */
    private void inputSubmitClick(View v) {
        Question question = questions.get(vm.getQuestionIndex());
        boolean result = inputAnswerBinding.editAnswer.getText().toString().equals(question.getQuestionAnswer());
        inputAnswerBinding.editAnswer.getText().clear();
        if (vm.isShowed()) {
            Toast.makeText(this, "invalid in " + vm.getTime(), Toast.LENGTH_SHORT).show();
            vm.setHelpTimes(vm.getHelpTimes() + 1);
        } else if (result) {
            vm.rightAnswersPP();
        } else
        {
            vm.setWrongTimes(vm.getWrongTimes() + 1);
        }
        vm.setShowed(false);
        if (vm.getQuestionIndex() >= questions.size() - 1) {
            vm.setQuestionIndex(-1);
            disableInputSubmit();
            showResult();
        } else {
            vm.questionIndexPP();
            textBinding.tvQuestion.setText(questions.get(vm.getQuestionIndex()).getQuestionText());
        }
    }


    private void showResult()
    {
        Toast.makeText(this, String.format("%s right, %s helped, %s wrong.", vm.getNumberOfRightAnswers(), vm.getHelpTimes(), vm.getWrongTimes()), Toast.LENGTH_LONG).show();
    }

    /**
     * 禁用输入区的按钮
     */
    private void disableInputSubmit() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            inputAnswerBinding.btnSubmit.setEnabled(false);
            inputAnswerBinding.btnHelp.setEnabled(false);
        } else {
            inputAnswerBinding.btnSubmitLand.setEnabled(false);
            inputAnswerBinding.btnHelpLand.setEnabled(false);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}


